import React, { Component, useState, useEffect } from 'react'
import { UdModalForm, UdTable, UdDateRangePicker, validators, http } from '@/lib'
import { Select, Icon, Spin, message } from 'antd'
import './style.scss'
import moment from 'moment'
import 'moment/locale/zh-cn.js'
import apis from '@/apis/SystemSettings'
import comApis from '@/apis'
import dayjs from 'dayjs'
import { WrappedFormUtils } from 'antd/lib/form/Form'
moment.locale('zh-cn')

const { Option } = Select

class QutaValidityCycleModalContent extends Component<IQutaValidityCycleModalContentProps, IQutaValidityCycleModalContentState> {
  private modalForm: WrappedFormUtils
  constructor(props) {
    super(props)
    this.state = {
      querying: false,
      firstQuotaCycleData: undefined,
      assessYears: [],
      assessTimeRange: [],
    }
  }

  render() {
    const { brandList, ...rest } = this.props
    return (
      <Spin spinning={this.state.querying}>
        <UdModalForm
          {...rest}
          getForm={(form) => this.modalForm = form}
          items={[
            {
              label: '品牌公司', id: 'brandCode', rules: [validators.required], render: () => {
                return (
                  <Select labelInValue={true} onChange={this.brandCodeChange}>
                    {brandList.map(({ value, title }) => <Option key={value} value={value}>{title}</Option>)}
                  </Select>
                )
              }
            },
            {
              label: '考核年度', id: 'year', rules: [validators.required], render: () => {
                return (
                  <Select onChange={this.yearChangeHandle}>
                    {this.state.assessYears.map(({ value, title }) => <Option key={value} value={value}>{title}</Option>)}
                  </Select>
                )
              }
            },
            { label: '起止时间', id: ['yearStartTime', 'yearEndTime'], render: () => {
              let render = this.state.assessTimeRange[0] ? dayjs(this.state.assessTimeRange[0]).format('YYYY-MM-DD') : ''
              render += this.state.assessTimeRange[1] ? '~' + dayjs(this.state.assessTimeRange[1]).format('YYYY-MM-DD') : ''
              return <div>{render || '--'}</div>
            } },
            { label: '', id: 'table', wrapperCol: { span: 24 }, render: <QutaValidityCycleTable timeLimitRange={this.state.assessTimeRange} dataSource={this.state.firstQuotaCycleData} /> },
          ]}
        />
      </Spin>
    )
  }

  public brandCodeChange = (value) => {
    // 选择品牌公司获取其考核年度
    this.setState({ querying: true, assessYears: [], assessTimeRange: [] })
    // 置空考核年度
    this.modalForm.setFieldsValue({year: undefined, 'yearStartTime|yearEndTime': undefined})
    const { key: brandCode } = value
    http.post(comApis.GetAssessYearByBrand, { brandCode }).then(res => {
      const assessYears = res.data?.map(item => ({ ...item, value: item.year, title: item.name })) || []
      this.setState({
        assessYears,
      })
    }).finally(() => {
      this.setState({
        querying: false,
      })
    })
  }

  public yearChangeHandle = (value) => {
    // 选择考核年度获取其最后周期数据，用于初始化列表周期数据
    this.setState({ querying: true })
    const brandInfo = this.modalForm.getFieldValue('brandCode')
    const brandCode = brandInfo?.key
    const params = { conditions: { brandCode, year: value }, page: 1, size: 1 }
    http.post(apis.QuotaValidityCycleList, params).then(res => {
      // 获取最后周期位置
      const lastCycleSort = res.data?.content[0]?.cycleSort + 1 || 1
      const firstQuotaCycleData = [{
        cycleSort: lastCycleSort,
        cycleName: '第' + lastCycleSort + '周期',
        cycleStartTime: undefined,
        cycleEndTime: undefined,
      }]
      this.setState({
        firstQuotaCycleData,
      })
    }).finally(() => {
      this.setState({ querying: false })
    })

    const yearInfo = this.state.assessYears.find(item => item.value == value) || {}
    const { startTime, endTime } = yearInfo
    // 给起止时间赋值，外部提交使用
    this.modalForm.setFieldsValue({'yearStartTime|yearEndTime': [startTime, endTime]})
    this.setState({
      assessTimeRange: [startTime, endTime],
    })
  }

}

export default QutaValidityCycleModalContent

interface IQutaValidityCycleModalContentProps {
  brandList: { value: string, title: string }[]
}

interface IQutaValidityCycleModalContentState {
  querying: boolean
  firstQuotaCycleData?: any[] | undefined
  assessYears: any[]
  assessTimeRange: any[]
}

/* 周期添加列表 */
function QutaValidityCycleTable(props) {
  const [dataSource, setDataSource] = useState([
    { cycleSort: 1, cycleName: '第1周期', cycleStartTime: undefined, cycleEndTime: undefined }
  ])

  useEffect(() => {
    props.dataSource && setDataSource(props.dataSource)
  }, [props.dataSource])

  const deleteHandle = (row) => {
    const newData = [...dataSource]
    let index = newData.findIndex((data) => data.cycleSort == row.cycleSort)
    newData.splice(index, 1)
    setDataSource(newData)
    props.onChange(newData)
  }

  const addHandle = () => {
    const newData = [...dataSource]
    const sort = newData[newData.length - 1].cycleSort + 1
    newData.push({
      cycleSort: sort,
      cycleName: '第' + sort + '周期',
      cycleStartTime: undefined,
      cycleEndTime: undefined,
    })
    setDataSource(newData)
  }

  const changeTableData = (row, values) => {
    if (!props.timeLimitRange || props.timeLimitRange.length == 0) {
      message.error('请先选择考核年度')
      return
    }
    const newData = [...dataSource]
    let index = newData.findIndex((data) => data.cycleSort == row.cycleSort)
    const cycleStartTime = values[0]
    const cycleEndTime = values[1]
    newData.splice(index, 1, { ...row, cycleStartTime, cycleEndTime })
    setDataSource(newData)
    props.onChange(newData)
  }

  const disabledCycleTime = (current) => {
    const { timeLimitRange } = props
    if (timeLimitRange && timeLimitRange.length > 0) {
      let minTime = timeLimitRange[0] && new Date(timeLimitRange[0]).getTime()
      let maxTime = timeLimitRange[1] && new Date(timeLimitRange[1]).getTime()
      return current && ( current < minTime ||  current > maxTime)
    }
  }

  const columns = [
    { title: '周期', dataIndex: 'cycleName' },
    {
      title: '周期起止时间', dataIndex: 'cycleStartTime', width: 260, render: (text, record) => {
        const endTime = record.cycleEndTime
        const value = [text ? moment(text) as any : undefined, endTime ? moment(endTime) as any : undefined]
        return <UdDateRangePicker value={value} onChange={(dates) => changeTableData(record, dates)} disabledDate={disabledCycleTime} valueFormat={['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59']} allowClear={false} />
      }
    },
    // { title: '结束年月', dataIndex: 'cycleEndTime' },
    {
      title: '', dataIndex: 'operate', className: 'minus-td', render: (text, record) => {
        return dataSource.length > 1 ? <Icon type="minus-circle" onClick={() => deleteHandle(record)} /> : ''
      }
    },
  ]
  return (
    <>
      <UdTable
        columns={columns}
        pagination={false}
        dataSource={dataSource}
        rowKey={(record, index) => index + ''}
      />
      <div className='add-quota-validity' onClick={addHandle}>
        <Icon type="plus" />
      </div>
    </>
  )
}
